import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, message } from 'antd';
import { ContentPackage, DATA_ENTRY, AdvancedSearch } from '../../comps';
import AddNew from '../PortfolioMnt/BookkeepingMnt/addNew';
import styles from './index.less';
import TrialTrade from './trialTrade';
import TrialResult from './trialResult';
import CashReport from '../reportingServices/cashManagementReport/cashReport';
import moment from 'moment';
import { formSelectData } from '../../utils/utils';

const { TabPane } = Tabs;
@Form.create()
class PortfolioTrialR extends PureComponent {
  state = {
    timeStamp: undefined, // 时间戳,用于现金报告跳转
    activeKey: '1', // tab显示标志位
    templateList: [], // 模板
    isReset: false, // 标记是否点击了“重置”后未重新查询
    productGroup: '', // 产品组
    product: [], // 产品
    productList: [], // 产品默认选项
    portfolio: [], // 组合
    template: '', // 模板
    pageStatus: 1,
    portfolioCodeList: [], // 产品
    portfolioCodeListName: [], // 产品名称
    portfolioCodeListC: [], // 未查询状态产品值
    portfolioCodeListNameC: [], //  未查询状态产品名称
  };

  componentDidMount() {
    // 模板字典
    const {
      globalM: {
        dataDictionary: { TRIAL_TRADE_TEMPLATE = [] },
      },
    } = this.props;
    this.setState({
      templateList: formSelectData(TRIAL_TRADE_TEMPLATE),
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.state.productList.length == 0 && nextProps.productAGroupM.products) {
      this.setState(
        {
          productList: nextProps.productAGroupM.products, // 列表下拉数据
        },
        () => {
          this.setproductInitial();
        },
      );
    }
    let reportInfo = sessionStorage.getItem('reportInfo');
    if (reportInfo) {
      // 从现金报告页面进入
      this.template.props.form.setFieldsValue({
        template: 'money',
      });
      this.setState(
        {
          template: 'money',
        },
        () => {
          reportInfo = JSON.parse(reportInfo);
          if (reportInfo.prouctGroupId || (reportInfo.portfolioCodeList && reportInfo.portfolioCodeList.length)) {
            // 判断是否需要直接查询
            this.setState(
              {
                timeStamp: new Date().getTime(),
                activeKey: '2',
                productGroup: reportInfo.prouctGroupId ? reportInfo.prouctGroupId : '',
                product: reportInfo.prouctGroupId ? [] : reportInfo.portfolioCodeList,
                portfolioCodeList: reportInfo.portfolioCodeList,
                portfolioCodeListName: reportInfo.portfolioCodeListName,
                portfolioCodeListC: reportInfo.portfolioCodeList,
                portfolioCodeListNameC: reportInfo.portfolioCodeListName,
              },
              () => {
                this.trialTrade.getList();
              },
            );
          } else {
            this.setState({
              productGroup: '',
              product: [],
              portfolioCodeList: [],
              portfolioCodeListName: [],
              portfolioCodeListC: [],
              portfolioCodeListNameC: [],
            });
          }
          if (!reportInfo.prouctGroupId) {
            this.productRef.props.form.setFieldsValue({
              product: reportInfo.portfolioKey,
              productGroup: '',
            });
          } else {
            this.productGroupRef.props.form.setFieldsValue({
              productGroup: reportInfo.prouctGroupId,
              product: [],
            });
          }
        },
      );
      sessionStorage.removeItem('reportInfo'); // 清空
    }
  }

  // 设置产品默认值
  setproductInitial = () => {
    this.productRef.props.form.setFieldsValue({
      product: [],
    });
    this.setState({
      product: [],
    });
  };

  // 产品组select变化
  productGroupChange = (e) => {
    // 选择产品组清空产品
    this.productRef.props.form.setFieldsValue({
      product: undefined,
    });
    this.setState({
      productGroup: e ? e.key : '',
      product: [],
    });
    // 现金报告组件参数
    if (e) {
      const {
        info: { children = [] },
      } = e;
      if (children.length > 0) {
        this.setState({
          portfolioCodeListC: children.map((x) => x.code),
          portfolioCodeListNameC: children.map((x) => `${x.code}-${x.name}`),
        });
      } else {
        message.warning('该组合下无产品');
      }
    } else {
      this.setState({
        portfolioCodeListC: [],
        portfolioCodeListNameC: [],
      });
    }
  };

  // 产品select变化
  productChange = (e) => {
    const arr = [];
    if (e) {
      e.info?.map((item) => {
        arr.push(item.portfolioCode);
      });
    }
    this.productGroupRef.props.form.setFieldsValue({
      productGroup: undefined,
    });
    this.setState({
      productGroup: '',
      product: arr,
    });
    // 现金报告组件参数
    if (e) {
      const { info = [] } = e;
      if (info.length > 0) {
        this.setState({
          portfolioCodeListC: info.map((x) => x.portfolioCode),
          portfolioCodeListNameC: info.map((x) => `${x.portfolioCode}-${x.portfolioName}`),
        });
      }
    } else {
      this.setState({
        portfolioCodeListC: [],
        portfolioCodeListNameC: [],
      });
    }
  };

  // 工具栏渲染
  renderToolbar() {
    const {
      form: { getFieldsValue, resetFields, setFieldsValue },
      loading,
      productAGroupM,
    } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'productGroup',
          type: DATA_ENTRY.PRODUCTGROUP,
          onChange: this.productGroupChange,
          onRef: (ref) => (this.productGroupRef = ref),
        },
        {
          dataIndex: 'product',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          onChange: this.productChange,
          multiple: true,
          onRef: (ref) => (this.productRef = ref),
        },
        {
          dataIndex: 'template',
          title: '模板',
          type: DATA_ENTRY.SELECT,
          dataSource: this.state.templateList,
          initialValue: 'BASE',
          onRef: (ref) => (this.template = ref),
        },
      ],
      onQuery: (e) => {
        if (!e.productGroup && !(e.product && e.product.length > 0)) {
          message.warning('请选择产品组或产品');
          return;
        }
        if (!e.template) {
          message.warning('请选择模板');
          return;
        }
        this.setState(
          {
            template: e.template,
            timeStamp: new Date().getTime(),
            activeKey: '2',
            isReset: false,
            portfolioCodeList: this.state.portfolioCodeListC,
            portfolioCodeListName: this.state.portfolioCodeListNameC,
          },
          () => {
            if (e.template != 'money') {
              // this.trialResult?.getResultList();

              setTimeout(() => {
                this.trialResult.getResultList();
              }, 500);
            }
            this.trialTrade.getList();
          },
        );
      },
      onClear: () => {
        resetFields();
        this.setproductInitial();
        this.setState({
          isReset: true,
          productGroup: '',
          portfolio: [],
        });
      },
    };

    return (
      <>
        <AdvancedSearch {...searchProps} />
      </>
    );
  }

  // tab切换时调用
  handleChangeTab = (value) => {
    this.setState({
      activeKey: value,
    });
  };

  // 新增按钮
  addNewChange = () => {
    this.setState({ pageStatus: 2 });
  };

  // 新增成功
  addNewSucc = () => {
    this.setState({ pageStatus: 1 });
    const { productGroup, product, template } = this.state;
    if ((productGroup || (product && product.length > 0)) && template) {
      this.trialTrade.refresh();
    }
  };

  // tab bar上额外的元素
  createBarExtraContent = () => {
    return this.state.template == 'money' ? (
      <div className='bar-tip'>
        <ExclamationCircleOutlined className='bar-icon' />
        <span>仅针对债券进行试算</span>
      </div>
    ) : (
      ''
    );
  };

  /***
   * 点击试算
   * @param {string} id
   */
  visualTryCompute = (id) => {
    this.props.dispatch({
      type: 'bondInformationM/virtualSubjectTrial',
      payload: { id },
      callback: (res) => {
        if (res.code === 0) {
          message.success('试算下达成功');
          // 重新查询试算交易
          this.trialTrade.getList();
          // 重新查询试算结果
          this.trialResult.getResultList();
        } else {
          message.error('试算下达失败');
        }
      },
    });
  };

  render() {
    const { activeKey, pageStatus, productGroup, product, portfolio, template, isReset, portfolioCodeList, portfolioCodeListName, timeStamp } = this.state;
    const dataObj = {
      productGroup,
      product,
      portfolio,
      template,
      isReset,
    };
    return (
      <ContentPackage
        title='组合试算'
        contentHtml={
          <div>
            <div className={styles.PortfolioTrialR} style={{ display: pageStatus == 1 ? 'block' : 'none' }}>
              {this.renderToolbar()}
              <Tabs activeKey={activeKey} onChange={this.handleChangeTab} tabBarExtraContent={this.createBarExtraContent()}>
                <TabPane tab='试算交易' key='1' forceRender={false}>
                  <TrialTrade visualTryCompute={this.visualTryCompute} dataObj={dataObj} onRef={(ref) => (this.trialTrade = ref)} addNewChange={(e) => this.addNewChange()} />
                </TabPane>
                <TabPane tab='试算结果' key='2' forceRender={false}>
                  {template == 'money' ? (
                    <CashReport type={'2'} storeName={{ portfolioCodeListName }} timeStamp={timeStamp} time={moment().format('YYYYMMDD')} portfolioCodeList={portfolioCodeList} />
                  ) : (
                    <TrialResult dataObj={dataObj} onRef={(ref) => (this.trialResult = ref)} />
                  )}
                </TabPane>
              </Tabs>
            </div>
            {pageStatus == 2 && (
              <div>
                <AddNew onClose={() => this.setState({ pageStatus: 1 })} onRefresh={this.addNewSucc} type={2} />
              </div>
            )}
          </div>
        }
      />
    );
  }
}
export default connect(({ portfolioTrialM, loading, productAGroupM, globalM }) => ({ portfolioTrialM, loading, productAGroupM, globalM }))(PortfolioTrialR);
